package com.zpdhy.summer;

import com.zpdhy.summer.service.Message;
import com.zpdhy.summer.service.SftpService;
import com.zpdhy.summer.service.impl.SftpServiceImpl;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainController implements Initializable, Message {

    @FXML
    Button myButton;
    @FXML
    TextArea myTextField;
    @FXML
    AnchorPane mainContainer;

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private SftpService sftpService;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
        sftpService = new SftpServiceImpl(this);
    }

    public void enterKeyUp(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER) {
            addLog();
        }
    }

    private void addLog() {
        appendStringToTextArea(dateFormat.format(new Date()) + "：start upload war...\n");
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                sftpService.uploadFile();
            }
        });

    }

    @FXML
    public void onAction(ActionEvent event) {
        addLog();
    }

    @Override
    public void appendStringToTextArea(final String str) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                // TODO 很重要 更新JavaFX的主线程的代码放在此处
                myTextField.appendText(str);
            }
        });

    }
}
